package com.yisu.expressway.onedollar.activity;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONObject;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.gson.reflect.TypeToken;
import com.will.network.images.round.CircleImageView;
import com.yisu.expressway.R;
import com.yisu.expressway.network.ApiClientHelper;
import com.yisu.expressway.network.ApiResult;
import com.yisu.expressway.network.ApiSetting;
import com.yisu.expressway.onedollar.model.OrderDetailForWinningVo;
import com.yisu.expressway.onedollar.model.OrderDetailObj;
import com.yisu.expressway.onedollar.model.UserAddressItem;
import com.yisu.expressway.onedollar.model.WinningRecord;
import com.yisu.expressway.onedollar.presenter.IOrderDetailPresenter;
import com.yisu.expressway.onedollar.presenter.impl.OrderDetailPresenterImpl;
import com.yisu.expressway.onedollar.view.IOrderDetailView;
import com.yisu.expressway.onedollar.widget.TitleView;
import com.yisu.expressway.utils.SpannableUtil;
import com.yisu.expressway.utils.StringUtil;
import com.yisu.expressway.utils.ToastUtil;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * Created by Kaven on 2016/12/9.
 */

public class OrderDetailActivity extends BasicActivity implements IOrderDetailView {
    private static final String EXTRA_KEY_ORDER_ID = "extra_key_order_id";
    private static final String TAG = OrderDetailActivity.class.getSimpleName();
    @Bind(R.id.rootView)
    protected View mRootView;
    @Bind(R.id.title_bar)
    protected TitleView mTitleView;

    @Bind(R.id.iv_goods_cover)
    protected ImageView mGoodsCoverIv;
    @Bind(R.id.tv_goods_name)
    protected TextView mGoodsNameTv;
    @Bind(R.id.tv_periodsnum)
    protected TextView mPeriodsNumTv;
    @Bind(R.id.tv_order_status)
    protected TextView mOrderStatusTv;
    @Bind(R.id.tv_luckNumber)
    protected TextView mLuckNumTv;
    @Bind(R.id.ll_remain)
    protected View mRemainView;
    @Bind(R.id.progressBar)
    protected ProgressBar progressBar;
    @Bind(R.id.tv_remain)
    protected TextView mRemainTv;
    @Bind(R.id.rl_winner_info)
    protected View mWinnerInfoView;
    @Bind(R.id.iv_winner_avatar)
    protected CircleImageView mAvatarCiv;
    @Bind(R.id.tv_winner_name)
    protected TextView mWinnerNameTv;
    @Bind(R.id.tv_winner_joinnum)
    protected TextView mWinnerJoinNumTv;
    @Bind(R.id.tv_order_join_time)
    protected TextView mOrderJoinTimeTv;
    @Bind(R.id.tv_order_join_num)
    protected TextView mOrderJoinNumTv;
    @Bind(R.id.tv_order_luckyNum)
    protected TextView mOrderLuckNumTv;
    @Bind(R.id.tv_order_no)
    protected TextView mOrderNoTv;
    @Bind(R.id.tv_order_cost)
    protected TextView mOrderCostTv;
    @Bind(R.id.tv_add_addr)
    protected TextView mAddAddrTv;
    @Bind(R.id.tv_order_join_again)
    protected TextView mJoinAgainTv;
    @Bind(R.id.divider5)
    protected View mDivideLineAddress;
    @Bind(R.id.rl_order_info_address)
    protected View mAddressView;
    @Bind(R.id.tv_consigneeName)
    protected TextView mConsigneeNameTv;
    @Bind(R.id.tv_consigneePhone)
    protected TextView mConsigneePhoneTv;
    @Bind(R.id.tv_address)
    protected TextView mAddressTv;
    @Bind(R.id.iv_go_address)
    protected ImageView mGoIv;
    @Bind(R.id.tv_see_more)
    protected TextView mLuckNumSeeMoreTv;
    private IOrderDetailPresenter mPresenter;
    private List<UserAddressItem> mUserAddressItems;

    public static void launch(Context context, long orderId) {
        Intent intent = new Intent(context, OrderDetailActivity.class);
        intent.putExtra(EXTRA_KEY_ORDER_ID, orderId);
        context.startActivity(intent);
    }

    @Override
    protected int getThemeId() {
        return R.style.OneDollarTheme;
    }

    @Override
    protected int getInflateLayoutId() {
        return R.layout.activity_one_dollar_order_detail;
    }

    @Override
    protected void initPresenter() {
        mPresenter = new OrderDetailPresenterImpl(this, this);
        mPresenter.init();
    }

    @Override
    protected void releasePresenter() {
        if (mPresenter != null) {
            mPresenter = null;
        }
    }

    @Override
    protected void getIntentData(Intent intent) {
        long orderId = intent.getLongExtra(EXTRA_KEY_ORDER_ID, -1);
        if (orderId < 0) {
            finish();
        }
        mPresenter.fetchOrderDetailInfo(orderId);
    }

    @Override
    protected void getSavedBundleData(Bundle bundle) {

    }

    @Override
    protected void initViews() {
        mRootView.setVisibility(View.GONE);
        getAddressList();
    }

    @Override
    protected void bindEvents() {
        mTitleView.setOnTitleBarClickEvent(new TitleView.OnTitleBarClickEvent() {
            @Override
            public void onLeftClick(View view) {
                finish();
            }

            @Override
            public void onTitleClick(View view) {

            }

            @Override
            public void onRightClick(View view) {

            }
        });
    }

    @Override
    protected boolean isNeedLogin() {
        return true;
    }

    @Override
    protected void onLoginStateChange(boolean login) {

    }

    @Override
    public void showToast(String toastMsg) {
        if (StringUtil.isNullOrEmpty(toastMsg)) {
            return;
        }
        ToastUtil.displayLongToastMsg(this, toastMsg);
    }

    @Override
    public void showPopDlg() {

    }

    @Override
    public void dismissPopDlg() {
    }

    @Override
    public void jump2NextPage() {
        OrderDetailObj orderDetailInfo = mPresenter.getOrderDetailInfo();
        if (orderDetailInfo == null) {
            return;
        }
        GoodsPurchaseActivity.launch(this, orderDetailInfo.nextGoodsNo);
    }

    @Override
    public void refreshView(boolean bSuc) {
        if (bSuc) {
            mRootView.setVisibility(View.VISIBLE);
            setTitleName();
            setGoodsView();
            setWinnerView();
            setOrderView();
            setAddressView();
            setBottomView();
        } else {
            mRootView.setVisibility(View.GONE);
        }
    }

    private void setTitleName() {
        OrderDetailObj orderDetailInfo = mPresenter.getOrderDetailInfo();
        if (orderDetailInfo == null) {
            return;
        }
        mTitleView.setTitle(getString(R.string.one_dollar_order_detail));
    }

    protected void changeOrderAddress(UserAddressItem item, final long orderId) {
        if (orderId <= 0 || item == null) {
            return;
        }
        Map<String, Object> params = new HashMap();
        params.put("address", item.address);
        params.put("area", item.area);
        params.put("city", item.city);
        params.put("province", item.province);
        params.put("consigneeName", item.consigneeName);
        params.put("consigneePhone", item.consigneePhone);
        params.put("orderId", orderId);
        ApiClientHelper.postApi(ApiSetting.changeOrderAddress(), new TypeToken<Object>() {
        }, new JSONObject(params), new Response.Listener<ApiResult<Object>>() {
            @Override
            public void onResponse(ApiResult<Object> result) {
                if (!result.success) {
                    ToastUtil.showMessage(OrderDetailActivity.this,
                            getString(R.string.one_dollar_user_address_insert_failed));
                }
                mPresenter.fetchOrderDetailInfo(orderId);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                ToastUtil.showMessage(OrderDetailActivity.this,
                        getString(R.string.one_dollar_user_address_insert_failed));
            }
        }, this);
    }

    private void getAddressList() {
        ApiClientHelper.postApi(ApiSetting.getUserAddressList(),
                new TypeToken<List<UserAddressItem>>() {
                }, "", new Response.Listener<ApiResult<List<UserAddressItem>>>() {
                    @Override
                    public void onResponse(ApiResult<List<UserAddressItem>> result) {
                        if (!result.success) {
                            return;
                        }
                        List<UserAddressItem> result1 = result.getResult();
                        if (result1 != null) {
                            mUserAddressItems = result.getResult();
                        }

                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                    }
                }, this);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (RESULT_OK == resultCode) {
            switch (requestCode) {
                case UserAddressBuildActivity.BUILD_TYPE_INSERT:
                    UserAddressItem userAddressItem = (UserAddressItem) data
                            .getSerializableExtra(UserAddressBuildActivity.EXTRA_KEY_RESULT);

                    long orderId = data
                            .getLongExtra(UserAddressBuildActivity.EXTRA_KEY_RESULT_ORDER_ID, -1);
                    changeOrderAddress(userAddressItem, orderId);
                    break;
                case UserAddressActivity.REQUEST_CODE_SELECT:
                    userAddressItem = (UserAddressItem) data
                            .getSerializableExtra(UserAddressActivity.EXTRA_KEY_RESULT);

                    orderId = data.getLongExtra(UserAddressActivity.EXTRA_KEY_RESULT_ORDER_ID,
                            -1);
                    changeOrderAddress(userAddressItem, orderId);
                default:
                    break;
            }
        }
    }

    private void setAddressView() {
        OrderDetailObj orderDetailInfo = mPresenter.getOrderDetailInfo();
        if (orderDetailInfo == null) {
            return;
        }
        if (TextUtils.isEmpty(orderDetailInfo.consigneeName)
                && TextUtils.isEmpty(orderDetailInfo.consigneePhone)) {
            mAddressView.setVisibility(View.GONE);
            mDivideLineAddress.setVisibility(View.GONE);
        } else {
            mGoIv.setVisibility(orderDetailInfo.deliverGoodsStatus == 1 ?View.GONE:View.VISIBLE);
            mDivideLineAddress.setVisibility(View.VISIBLE);
            mAddressView.setVisibility(View.VISIBLE);
            mConsigneeNameTv.setText(orderDetailInfo.consigneeName);
            mConsigneePhoneTv.setText(orderDetailInfo.consigneePhone);
            StringBuilder builder = new StringBuilder();
            if (!TextUtils.isEmpty(orderDetailInfo.province)) {
                builder.append(orderDetailInfo.province);
            }
            if (!TextUtils.isEmpty(orderDetailInfo.city)) {
                builder.append(orderDetailInfo.city);
            }
            if (!TextUtils.isEmpty(orderDetailInfo.area)) {
                builder.append(orderDetailInfo.area);
            }
            if (!TextUtils.isEmpty(orderDetailInfo.address)) {
                builder.append(orderDetailInfo.address);
            }
            if (!TextUtils.isEmpty(builder.toString())) {
                mAddressTv.setText(builder.toString());
            }

        }
    }

    @Override
    public void jump2SelectAddressPage() {
        OrderDetailObj orderDetailInfo = mPresenter.getOrderDetailInfo();
        if (orderDetailInfo == null) {
            return;
        }
        if (orderDetailInfo.deliverGoodsStatus ==1){
            return;
        }
        if (mUserAddressItems == null || mUserAddressItems.isEmpty()) {
            UserAddressBuildActivity.launch(this,
                    UserAddressBuildActivity.BUILD_TYPE_INSERT, null, true, orderDetailInfo.orderId);
        } else {
            UserAddressActivity.launch(this, UserAddressActivity.REQUEST_CODE_SELECT,
                    orderDetailInfo.orderId);
        }

    }

    @OnClick({R.id.tv_order_join_again, R.id.tv_add_addr, R.id.tv_see_more, R.id.rl_order_info_address})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_order_join_again:
                jump2NextPage();
                break;
            case R.id.tv_add_addr:
                jump2SelectAddressPage();
                break;
            case R.id.tv_see_more:
                jump2LuckNumDetailPage();
                break;
            case R.id.rl_order_info_address:
                jump2SelectAddressPage();
                break;
            default:
                break;
        }
    }

    private void jump2LuckNumDetailPage() {
        OrderDetailObj orderDetailInfo = mPresenter.getOrderDetailInfo();
        if (orderDetailInfo == null) {
            return;
        }
        LuckyNumDetailActivity.launch(this, orderDetailInfo.luckyNums, orderDetailInfo.orderDetailForGoodsInfoVo.goodsName, orderDetailInfo.orderDetailForGoodsInfoVo.periodsNum);
    }

    private void setBottomView() {
        OrderDetailObj orderDetailInfo = mPresenter.getOrderDetailInfo();
        if (orderDetailInfo == null) {
            mJoinAgainTv.setVisibility(View.GONE);
            mAddAddrTv.setVisibility(View.GONE);
            return;
        }
        mJoinAgainTv.setVisibility(orderDetailInfo.isExistNext == 1 ? View.VISIBLE : View.GONE);
        mAddAddrTv.setVisibility(orderDetailInfo.isNeedsAddress == 1 ? View.VISIBLE : View.GONE);
    }

    private void setOrderView() {
        OrderDetailObj orderDetailInfo = mPresenter.getOrderDetailInfo();
        if (orderDetailInfo == null) {
            return;
        }
        String format = String.format(getString(R.string.one_dollar_join_time),
                orderDetailInfo.createTime);
        mOrderJoinTimeTv.setText(SpannableUtil.setHighLight(this, format, format.substring(0, 5),
                R.color.oneDollarTextGrey));
        format = String.format(getString(R.string.one_dollar_join_count),
                orderDetailInfo.joinNum);
        mOrderJoinNumTv.setText(SpannableUtil.setHighLight(this, format, format.substring(0, 5),
                R.color.oneDollarTextGrey));

        String luckyNums = orderDetailInfo.luckyNums;
        if (!TextUtils.isEmpty(luckyNums)) {
            String[] split = luckyNums.split(",");
            mLuckNumSeeMoreTv.setVisibility(split.length > 3 ? View.VISIBLE : View.GONE);
            StringBuilder stringBuilder = new StringBuilder();
            if (split.length > 3){
                for (int i = 0 ; i< 3; i++){
                    stringBuilder.append(split[i]).append(" ");
                }
            }else {
                String s = luckyNums.replaceAll(",", " ");
                stringBuilder.append(s);
            }

            mOrderLuckNumTv.setText(stringBuilder.toString());
        }


        format = String.format(getString(R.string.one_dollar_order_no),
                orderDetailInfo.orderId);
        mOrderNoTv.setText(SpannableUtil.setHighLight(this, format, format.substring(0, 5),
                R.color.oneDollarTextGrey));
        format = String.format(getString(R.string.pay_online_cost), orderDetailInfo.orderAmount);
        mOrderCostTv.setText(SpannableUtil.setHighLight(this, format, format.substring(0, 5),
                R.color.oneDollarTextGrey));
    }

    private void setWinnerView() {
        OrderDetailObj orderDetailInfo = mPresenter.getOrderDetailInfo();
        if (orderDetailInfo == null || orderDetailInfo.orderDetailForWinningVo == null) {
            mWinnerInfoView.setVisibility(View.GONE);
            return;
        }

        mWinnerInfoView.setVisibility(orderDetailInfo.grabStatus == 1 ? View.VISIBLE : View.GONE);
        if (orderDetailInfo.grabStatus == 1) {
            OrderDetailForWinningVo orderDetailForWinningVo = orderDetailInfo.orderDetailForWinningVo;
            String userHeadImg = orderDetailForWinningVo.userHeadImg;
            if (!TextUtils.isEmpty(userHeadImg)) {
                String[] split = userHeadImg.split(",");
                if (split.length > 0) {
                    String picShow = split[0];
                    Glide.with(this).load(picShow).asBitmap().placeholder(R.drawable.avatar_default)
                            .diskCacheStrategy(DiskCacheStrategy.ALL).centerCrop()
                            .animate(R.anim.fade_in_image).into(mAvatarCiv);
                }
            } else {
                mAvatarCiv.setImageDrawable(getResources().getDrawable(R.drawable.avatar_default));
            }
            mWinnerNameTv.setText(orderDetailForWinningVo.userName);
            String format = String.format(getString(R.string.one_dollar_join_count_2),
                    orderDetailForWinningVo.joinNum);
            mWinnerJoinNumTv.setText(format);
        }

    }

    private void setGoodsView() {
        OrderDetailObj orderDetailInfo = mPresenter.getOrderDetailInfo();
        if (orderDetailInfo == null) {
            return;
        }
        String goodsPic = orderDetailInfo.orderDetailForGoodsInfoVo.goodsPic;
        if (!TextUtils.isEmpty(goodsPic)) {
            String[] split = goodsPic.split(",");
            if (split.length > 0) {
                String picShow = split[0];
                Glide.with(this).load(picShow).asBitmap().placeholder(R.drawable.pic_loading)
                        .diskCacheStrategy(DiskCacheStrategy.ALL).centerCrop()
                        .animate(R.anim.fade_in_image).into(mGoodsCoverIv);
            }
        } else {
            mGoodsCoverIv.setImageDrawable(getResources().getDrawable(R.drawable.pic_loading));
        }
        mGoodsNameTv.setText(orderDetailInfo.orderDetailForGoodsInfoVo.goodsName);
        String format = String.format(getString(R.string.one_dollar_periods_num_1),
                orderDetailInfo.orderDetailForGoodsInfoVo.periodsNum);
        mPeriodsNumTv.setText(format);
        int grabStatus = orderDetailInfo.grabStatus;
        mLuckNumTv.setVisibility(grabStatus == 3 ? View.GONE : View.VISIBLE);
        mRemainView.setVisibility(grabStatus == 3 ? View.VISIBLE : View.GONE);
        switch (grabStatus) {
            case 1:
                mOrderStatusTv.setText(getString(R.string.one_dollar_order_status_not_winning));
                format = String.format(getString(R.string.one_dollar_announced_num),
                        orderDetailInfo.orderDetailForWinningVo.luckyNum);
                mLuckNumTv.setText(format);
                break;
            case 2:
                mOrderStatusTv.setText(getString(R.string.one_dollar_order_status_winning));
                format = String.format(getString(R.string.one_dollar_winning_num),
                        orderDetailInfo.orderDetailForWinningVo.luckyNum);
                mLuckNumTv.setText(format);
                break;
            case 3:
                mOrderStatusTv.setText(getString(R.string.one_dollar_order_status_announcing));
                progressBar.setMax((int) orderDetailInfo.totalJoinNum);
                progressBar.setProgress((int) orderDetailInfo.totalJoinNum
                        - (int) orderDetailInfo.surplusJoinNum);
                format = String.format(getString(R.string.one_dollar_join_remain),
                        orderDetailInfo.surplusJoinNum);

                mRemainTv.setText(SpannableUtil.setHighLight(this, format, format.substring(0, 2),
                        R.color.oneDollarTextGrey));
                break;
        }

    }

}
